<?php

namespace Orchid\Core;

use Illuminate\Support\Facades\DB;
use Orchid\Core\Service\ExecuteService;

class DBExecuteService implements ExecuteService
{
    /**
     * 创建表
     *
     * @param $tableName
     * @param $columns
     */
    public function create($tableName, $columns)
    {
        $createArr = [];
        $createSql = '';
        foreach ($columns as $item) {
            if (empty($item)) {
                return false;
            }

            array_push($createArr, $this->initColumn($item));
        }

        if (empty($createArr)) {
            return false;
        }

        $createSql .= "`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT," . PHP_EOL; // 默认id做主键
        foreach ($createArr as $item) {
            $createSql .= "  `{$item['name']}` {$item['type']}({$item['size']}) {$item['default']} {$item['nullAble']} COMMENT '{$item['comment']}'," . PHP_EOL;
        }

        $sql = file_get_contents(ROOT_PATH . '/resources/template/CreateTable');
        $sql = str_replace('${tableName}', $tableName, $sql);
        $sql = str_replace('${tableContent}', substr($createSql, 0, strlen($createSql) - 1), $sql);

        if ($this->delete($tableName) && DB::statement($sql)) {
            return true;
        }
        return false;
    }

    /**
     * 初始化栏目
     *
     * @param $item
     * @return array
     */
    private function initColumn($item)
    {
        list($name, $type, $size, $nullAble, $default, $comment) = $item;
        return [
            'name'     => $name,
            'type'     => $type,
            'size'     => $size,
            'default'  => $default ? 'DEFAULT' . $default : '',
            'nullAble' => $nullAble ? '' : 'NOT NULL',
            'comment'  => $comment ? $comment : ''
        ];
    }

    /**
     * 删除表
     *
     * @param $sql
     */
    public function delete($tableName)
    {
        DB::delete("DROP TABLE IF EXISTS $tableName");
    }

    /**
     * 查询
     *
     * @param $sql
     */
    public function select($sql)
    {

    }
}
